package qx.hyj.petrescue.intercept;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import qx.hyj.petrescue.exception.TokenErrorException;
import qx.hyj.petrescue.util.JWTUtil;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@Component
public class TokenIntercept implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(TokenIntercept.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = null;
        String uri = request.getRequestURI();
        String method = request.getMethod();
        logger.info("拦截器检测到请求: {} {}", method, uri); // 重点记录
            //获取请求头中的token
            token = request.getHeader("token");

            if (token == null) {
                //获取请求中的所有cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    //获取名为token的cookie
                    List<Cookie> list = Arrays.stream(cookies)
                            .filter(cookie -> "token".equals(cookie.getName()))
                            .collect(Collectors.toList());

                    token = list.get(0).getValue();
                    System.out.println("token2:" + token);
                }
            }

            //如果token不为空
            if (token != null) {
                try {
                    //获取token中的用户id
                    Integer id = JWTUtil.getUserId(token);
                    //将用户id存入request中
                    request.setAttribute("id", id);  // 方便每次请求获得id
                    return true;
                } catch (TokenErrorException e) {
                    //如果token错误，则返回401状态码
                    response.setStatus(401);
                    response.getWriter().write(e.getMessage());
                    System.err.println(e.getMessage());
                    return false;
                }
            }

        return false;  // 这里改为true，放行所有请求，方便调试
    }
}